package com.yunyouyi.cpicture.infrastructure.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yunyouyi.cpicture.infrastructure.config.CosClientConfig;
import com.yunyouyi.cpicture.infrastructure.exception.BusinessException;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.infrastructure.api.CosManager;
import com.yunyouyi.cpicture.infrastructure.manager.upload.model.dto.file.UploadPictureDTO;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 图片上传模板
 */
@Slf4j
public abstract class PictureUploadTemplet {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;//客户端

    /**
     * 清理临时文件
     */
    private static void deleteTempFile(File file) {
        if (file != null) {
            //删除临时文件
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error{}", file.getAbsolutePath());
            }
        }
    }

    public UploadPictureDTO uploadPicture(Object inputSource, String uploadPathPrefix) {
        //1.校验图片
        validPicture(inputSource);
        //2.图片上传地址
        String UUID = RandomUtil.randomString(10);
        String originalFilename = getOriginFilename(inputSource);
        //3.拼接文件上传路径
        String suffix = FileUtil.getSuffix(originalFilename);
        log.info("上传文件后缀{}", suffix);
        if(suffix.isEmpty()){
            suffix = "png";
        }
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), UUID, suffix);
        log.info("上传文件名{}",uploadFileName);
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        //4.解析结果并返回
        File file = null;
        try {
            //5.创建临时文件
            file = File.createTempFile(uploadPath, null);
            //6.处理文件来源
            processFile(inputSource, file);
            //7.上传文件到对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //8.获取图片信息对象，封装返回结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //获取处理后的图片信息对象
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            if(processResults == null || processResults.getObjectList()==null){
                return buildResult(imageInfo, uploadPath, originalFilename, file);
            }
            List<CIObject> objectList = processResults.getObjectList();

            if(CollUtil.isNotEmpty(objectList)){
                //获取压缩后的图片信息
                CIObject compressedCiObject =  objectList.get(0);
                log.info("压缩处理后的信息{}",compressedCiObject);
                //获取缩小图的信息
                CIObject thumbnailCiObject = compressedCiObject;
                if(objectList.size() > 1){
                    thumbnailCiObject = objectList.get(1);
                }
                return buildResult(originalFilename,compressedCiObject,thumbnailCiObject);
            }
            return buildResult(imageInfo, uploadPath, originalFilename, file);
        } catch (IOException e) {
            log.error("图片上传到对象存储失败{}", uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            //9.临时文件清理
            deleteTempFile(file);
        }
    }



    protected abstract void processFile(Object inputSource, File file);

    protected abstract String getOriginFilename(Object inputSource);

    protected abstract void validPicture(Object inputSource);
    /**
     * 封装返回结果
     *
     * @param originalFilename
     * @param compressedCiObject
     * @return 对象存储返回的图片信息
     */
    private UploadPictureDTO buildResult(String originalFilename, CIObject compressedCiObject,CIObject thumbnailCiObject) {
        //计算宽高
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = picWidth * 1.0 / picHeight;
        //封装返回结果
        UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
        uploadPictureDTO.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureDTO.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureDTO.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureDTO.setPicWidth(picWidth);
        uploadPictureDTO.setPicHeight(picHeight);
        uploadPictureDTO.setPicScale(picScale);
        uploadPictureDTO.setPicFormat(compressedCiObject.getFormat());
        //设置缩率图地址
        uploadPictureDTO.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        //返回可访问地址
        return uploadPictureDTO;
    }
    /**
     * 封装返回结果
     *
     * @param imageInfo
     * @param uploadPath
     * @param originalFilename
     * @param file
     * @return 对象存储返回的图片信息
     */
    private UploadPictureDTO buildResult(ImageInfo imageInfo, String uploadPath, String originalFilename, File file) {
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = picWidth * 1.0 / picHeight;
        UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
        uploadPictureDTO.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureDTO.setPicName(FileUtil.mainName(originalFilename));
        uploadPictureDTO.setPicSize(FileUtil.size(file));
        uploadPictureDTO.setPicWidth(picWidth);
        uploadPictureDTO.setPicHeight(picHeight);
        uploadPictureDTO.setPicScale(picScale);
        uploadPictureDTO.setPicFormat(imageInfo.getFormat());
        return uploadPictureDTO;
    }

}
